<template>
  <el-upload
    class="upload-demo"
    :action="action"
    :headers="uploadHeader"
    :show-file-list="false"
    :on-success="uploadFileSuccess"
    :before-upload="beforeUpload"
    :limit="limit"
    :accept="accept"
    :disabled="disabled"
  >
    <div style="text-align: left">
      <el-button size="small" type="primary" :loading="loading" v-if="canUpload">
        {{file ? editFileText : uploadFileText}}
      </el-button>
      <div class="file mgt10" v-loading="loading" v-if="fileName" @click="openFile">
        <i class="el-icon-tickets" style="margin-right: 5px"></i>
        <span >{{fileName}}</span>
      </div>

    </div>



  </el-upload>
</template>

<script>

import {getToken} from "@/utils/auth";

export default {
  name: "UploadMiddleFile",
  computed: {
    fileName() {
      return this.file.replace(/[^\\/]*[\\/]+/g,'');
    }
  },
  props:{
    action: {
      type: String,
      default: process.env.VUE_APP_BASE_API + '/middleWorkOrder/uploadFile',
    },
    uploadHeader: {
      type: Object,
      default: function(){
        return {
          Authorization: 'Bearer ' + getToken(),
        }
      }
    },
    limit:{
      type: Number,
      default: 1024 * 10, // 限制大小10m以下
    },
    accept:{
      type: String,
      default: '.pdf',
    },
    file:{
      type: String,
      default: '',
    },
    dataObj: {
      type: Object,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    canUpload: {
      type: Boolean,
      default: true,
    },
    uploadFileText: {
      type: String,
      default: '上传文件',
    },
    editFileText: {
      type: String,
      default: '修改文件',
    },
  },
  data(){
    return {
      fileList: [],
      loading: false,
    }
  },
  methods:{
    // 上传处理
    uploadFileSuccess(res, file) {
      this.loading = false
      if (res.error === 0) {
        this.$emit('uploadFileSuccess',res.info.fileUrl)
        this.$successMessage(res.message)
      } else {
        this.$errorMessage(res.message);
      }
    },
    beforeUpload(){
      this.loading = true
      return true
    },
    openFile(){
      window.open(this.file, '_blank')
    },
  },

}
</script>

<style scoped lang="scss">

.file:hover{
  color: #1890ff;
}
</style>
